//
//  BRCancellationViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2022/2/11.
//  Copyright © 2022 Brezze GWG. All rights reserved.
//

#import "BRCancellationViewController.h"
#import "GXJWebViewController.h"
#import "BRCustiomAlertView.h"

@interface BRCancellationViewController ()
{
    UIButton *_policyBtn;
    UIScrollView *_scrollView;
}
@end

@implementation BRCancellationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUI];
}

- (void)requestToNext {
    
    if (!_policyBtn.isSelected) {
        [BRHud showAuto:Localized(@"Cancellation_agreeToast")];
        CGFloat sc_y = _scrollView.contentSize.height - _scrollView.bounds.size.height;
        [_scrollView setContentOffset:CGPointMake(0, sc_y) animated:YES];
        return;
    }
    
    // 显示二次确认弹窗
    BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"Cancellation_Title") subTitle:Localized(@"Cancellation_confirmMessage") cancelStr:Localized(@"public_cancel") succStr:Localized(@"Cancellation_IamSure") cancelAction:^{
        // 取消操作，不做任何处理
    } successAction:^{
        // 确认注销，调用注销接口
        [self performCancellation];
    } showBC:YES];
    
    [self.view addSubview:alertV];
}

/// 执行注销操作
- (void)performCancellation {
    [BRHud showInView:self.view];
    // 使用新的注销接口：POST /sw/app/user/cancel/account，不需要传参
    [[BRRequestManager shared] POST:@"/sw/app/user/cancel/account" params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        [BRHud hiddenInView:self.view];
        [BRHud showAuto:Localized(@"public_success") inView:self.view];
        // 注销成功后清空所有用户信息并返回到登录页面
        [self jk_performAfter:2 block:^{
            [USERManager logoutClean];
            [USERManager toChangeRootVC];
        }];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
        // 显示错误信息（确保即使HTTP 200但有错误信息时也能显示）
        if (errMsg && errMsg.length > 0) {
            [BRHud showAuto:errMsg inView:self.view];
        } else {
            [BRHud showAuto:Localized(@"public_requestFailed") ?: @"请求失败" inView:self.view];
        }
    }];
    
}

- (void)deleteAccount {
    WS(weakSelf);
    [BRHud showInView:self.view];
    [[BRRequestManager shared] DELETE:@"/api/users" params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        [BRHud hiddenInView:weakSelf.view];
        
        [weakSelf jk_performAfter:2 block:^{
            [weakSelf pop];
        }];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:weakSelf.view];
    }];
}

- (void)clickPolicyBtn:(UIControl *)btn {
    _policyBtn.selected = !_policyBtn.selected;
}



#pragma mark - Action --
- (void)nextStep {
    
    [self requestToNext];
    
}

- (void)toPolicy {
    [self.view endEditing:YES];
    
    // 使用新的协议URL生成方法，根据当前语言动态生成
    NSString *url = [BRTools br_agreementURLWithType:0];
    NSString *titleStr = Localized(@"set_terms");
    GXJWebViewController *webView = [[GXJWebViewController alloc] init];
    webView.url = url ;
    [webView initWhiteBarWithTitle:titleStr isBack: YES];
    webView.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:webView animated:YES completion:nil];
}

- (void)pop {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UI --
- (void)setUI {
    
    self.view.backgroundColor = UIColorWhite;
    [self br_createTop:Localized(@"Cancellation_Title")];
    
    
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = UIColorWhite;
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.mas_equalTo(82 + kSafeAreaBottomHeight);
    }];
    
    UIView *line = [BRToolsView getLineView:UIColorMake(210, 216, 226)];
    [bottomView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.mas_equalTo(0.5);
    }];
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextBtn setTitle:Localized(@"Cancellation_IamSure") forState:UIControlStateNormal];
    UIImage *bgImg = UIImage.qd_homeScanBtnImage;
    [nextBtn setBackgroundImage:bgImg forState:UIControlStateNormal];
    nextBtn.layer.cornerRadius = 26;
    nextBtn.layer.masksToBounds = YES;
    [nextBtn setBackgroundColor:UIColorMake(0, 218, 242)];
//    UIImage *bgImg = UIImage.qd_homeScanBtnImage;
    nextBtn.layer.masksToBounds = YES;
//    [nextBtn setBackgroundImage:bgImg forState:UIControlStateNormal];
    nextBtn.titleLabel.font = [UIFont br_fontB:17];
    [bottomView addSubview:nextBtn];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.width.mas_equalTo(kScreenWidth - 32);
        make.left.equalTo(self.view).offset(16);
        make.top.offset(15);
    }];
    
    [nextBtn addTarget:self action:@selector(nextStep) forControlEvents:UIControlEventTouchUpInside];
    
//    YYLabel *resendLabel = [YYLabel new];
//    resendLabel.font = [UIFont br_fontM:14];
//    resendLabel.numberOfLines = 0;
//    resendLabel.textAlignment = NSTextAlignmentCenter;
//    resendLabel.textColor = UIColor.qd_titleTextColor;
//    resendLabel.preferredMaxLayoutWidth = kScreenWidth - 50;//100
//    WS(weakSelf);
//    NSString *agreeStr = @"I have read and agreed to ";
//    NSString *buttonStr = @"<用户注销协议>";
//    NSMutableAttributedString *resebdStr = [[NSMutableAttributedString alloc] initWithString: [NSString stringWithFormat:@"%@ %@.",agreeStr,buttonStr]];
//    resendLabel.text = [NSString stringWithFormat:@"%@ %@.",agreeStr,buttonStr];
//    [resendLabel sizeToFit];
//
//    [resebdStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(resebdStr.length-buttonStr.length-1, buttonStr.length) ];
//
//    resebdStr.yy_color = UIColor.qd_titleTextColor;
////    resebdStr.yy_font = [UIFont br_fontM:10];
//    [resebdStr yy_setTextHighlightRange:NSMakeRange(resebdStr.length-buttonStr.length - 1, buttonStr.length) color:UIColor.qd_tintColor3 backgroundColor:UIColorClear tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
//        [weakSelf toPolicy];
//        NSLog(@"0");
//    }];
//
//    resendLabel.attributedText = resebdStr;
//    [self.view addSubview:resendLabel];
//    [resendLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(nextBtn).offset(4);
//        make.right.equalTo(nextBtn);
//        make.bottom.equalTo(nextBtn.mas_top).offset(-7.5);
//
//    }];
    
    // 内容区域
    UIScrollView *sView = [[UIScrollView alloc] init];
    sView.showsVerticalScrollIndicator = NO;
    [self.view insertSubview:sView atIndex:0];
    [sView  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(kSafeAreaTopHeight);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(bottomView.mas_top).offset(0);
    }];
    _scrollView = sView;
    
    UIView *contentView  = [UIView new];
    contentView.backgroundColor = UIColorClear;
    [sView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(sView);
        make.width.mas_equalTo(kScreenWidth);
    }];
    
    UIImageView *topImg = [[UIImageView alloc] initWithImage:UIImageMake(@"set_warning")];
    [contentView addSubview:topImg];
    [topImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(85);
        make.centerX.offset(0);
        make.top.offset(28);
    }];
    
    UIView *firstTextView = [[UIView alloc] init];
    firstTextView.backgroundColor = UIColorMake(244,244,246);
    firstTextView.layer.cornerRadius = kCorners;
    firstTextView.layer.masksToBounds = YES;
    [contentView addSubview:firstTextView];
    [firstTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(topImg.mas_bottom).offset(28);
    }];
    
    UIView *secTextView = [[UIView alloc] init];
    secTextView.backgroundColor = UIColorMake(244,244,246);
    secTextView.layer.cornerRadius = kCorners;
    secTextView.layer.masksToBounds = YES;
    [contentView addSubview:secTextView];
    [secTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(firstTextView.mas_bottom).offset(10);
    }];
    UIColor *textColor = UIColorText1;
    UIFont *font = [UIFont br_fontM:14];
    QMUILabel *fLabel = [[QMUILabel alloc] init];
    fLabel.font = font;
    fLabel.textColor = textColor;
    fLabel.text = Localized(@"Cancellation_termsTitle");
    fLabel.textAlignment = NSTextAlignmentLeft;
    fLabel.numberOfLines = 0;
    [firstTextView addSubview:fLabel];
    [fLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.offset(16);
        make.right.offset(-16);
    }];
    
    NSArray *subTexts = @[Localized(@"Cancellation_terms01"),Localized(@"Cancellation_terms02"),Localized(@"Cancellation_terms03")];
    QMUILabel *oneLabel;
    for (int i = 0; i < subTexts.count; i++) {
        QMUILabel *label = [[QMUILabel alloc] init];
        label.font = font;
        label.textColor = textColor;
        label.text = subTexts[i];
        label.textAlignment = NSTextAlignmentLeft;
        label.numberOfLines = 0;
        [firstTextView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(30);
            make.right.offset(-16);
            make.height.mas_greaterThanOrEqualTo(28);
            if (i == 0) {
                make.top.equalTo(fLabel.mas_bottom).offset(8);
            }else {
                make.top.equalTo(oneLabel.mas_bottom).offset(8);
            }
            if (i == subTexts.count - 1) {
                make.bottom.offset(-16);
            }
        }];
        
        oneLabel = label;
        
        UIView *dot = [[UIView alloc] init];
        dot.backgroundColor = textColor;
        dot.layer.cornerRadius = 4;
        dot.layer.masksToBounds = YES;
        [firstTextView addSubview:dot];
        [dot mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(label).offset(10);
            make.right.equalTo(label.mas_left).offset(-8);
            make.height.width.mas_equalTo(8);
        }];
    }
    NSString *sText = [NSString stringWithFormat:@"%@\n\n%@",Localized(@"Cancellation_orderOver"),Localized(@"Cancellation_cancelAfterText")];
    QMUILabel *sLabel = [[QMUILabel alloc] init];
    sLabel.font = font;
    sLabel.textColor = textColor;
    sLabel.text = sText;
    sLabel.textAlignment = NSTextAlignmentLeft;
    sLabel.numberOfLines = 0;
    [secTextView addSubview:sLabel];
    [sLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.offset(16);
        make.right.bottom.offset(-16);
    }];
    
    // 48小时登录限制提示
    UIView *loginRestrictionView = [[UIView alloc] init];
    loginRestrictionView.backgroundColor = UIColorMake(244,244,246);
    loginRestrictionView.layer.cornerRadius = kCorners;
    loginRestrictionView.layer.masksToBounds = YES;
    [contentView addSubview:loginRestrictionView];
    [loginRestrictionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(secTextView.mas_bottom).offset(10);
    }];
    
    QMUILabel *restrictionLabel = [[QMUILabel alloc] init];
    restrictionLabel.font = font;
    restrictionLabel.textColor = textColor;
    restrictionLabel.text = Localized(@"Cancellation_loginRestriction");
    restrictionLabel.textAlignment = NSTextAlignmentLeft;
    restrictionLabel.numberOfLines = 0;
    [loginRestrictionView addSubview:restrictionLabel];
    [restrictionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.offset(16);
        make.right.bottom.offset(-16);
    }];
    
    QMUILabel *agreeTitle = [[QMUILabel alloc] init];
    agreeTitle.font = font;
    agreeTitle.textColor = textColor;
    agreeTitle.text = Localized(@"Cancellation_deleteNotify");
    agreeTitle.numberOfLines = 0;
    agreeTitle.textAlignment = NSTextAlignmentCenter;
    [contentView addSubview:agreeTitle];
    [agreeTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(loginRestrictionView.mas_bottom).offset(28);
    }];
    
    // 协议
    UIButton *policyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [policyBtn setImage:[UIImage imageNamed:@"set_unagree"] forState:UIControlStateNormal];
    [policyBtn setImage:[UIImage imageNamed:@"set_agree"] forState:UIControlStateSelected];
    [contentView addSubview:policyBtn];
    [policyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(16);
        make.top.equalTo(agreeTitle.mas_bottom).offset(11);
        make.left.offset(47);
    }];
//    [policyBtn addTarget:self action:@selector(clickPolicyBtn:) forControlEvents:UIControlEventTouchUpInside];
    policyBtn.userInteractionEnabled = NO;
    _policyBtn = policyBtn;
    
    UIControl *btn = [[UIControl alloc] init];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(policyBtn);
        make.width.height.mas_equalTo(50);
        make.centerY.equalTo(policyBtn);
    }];
    [btn addTarget:self action:@selector(clickPolicyBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    YYLabel *agreeMsg = [YYLabel new];
    agreeMsg.font = [UIFont br_fontM:11];
    agreeMsg.numberOfLines = 0;
    agreeMsg.preferredMaxLayoutWidth = kScreenWidth - 100.;//100
    [contentView addSubview:agreeMsg];
    [agreeMsg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(policyBtn.mas_right).offset(8);
        make.right.offset(-16);
        make.top.equalTo(policyBtn).offset(0);
//        make.height.mas_equalTo(40);
        make.bottom.offset(-28);
    }];
    WS(weakSelf);
    NSString *agreeStr = Localized(@"Cancellation_agreementText");
    NSMutableAttributedString *agreeAttStr = [[NSMutableAttributedString alloc] initWithString:agreeStr];
    [agreeMsg sizeToFit];
    
    [agreeAttStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, agreeStr.length) ];
    agreeAttStr.yy_color = UIColorMake(56, 56, 56);
    agreeAttStr.yy_font = [UIFont br_fontM:10];
    [agreeAttStr yy_setTextHighlightRange:NSMakeRange(0, agreeStr.length) color: UIColorMake(56, 56, 56) backgroundColor:UIColor.whiteColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf toPolicy];
        NSLog(@"0");
    }];
    agreeMsg.attributedText = agreeAttStr;
}

- (void)createTop {
    
    UIView *top = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kSafeAreaTopHeight)];
    top.backgroundColor = UIColor.qd_backgroundColor;
    [self.view addSubview:top];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, KStatusBarHeight, 54, 44);
    [backBtn setImage:UIImageMake(@"arrow_left_gary54") forState:UIControlStateNormal];
    [top addSubview:backBtn];
    [backBtn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *titleLbel = [[UILabel alloc] init];
    titleLbel.text  = Localized(@"Cancellation_Title");
    titleLbel.textColor = UIColor.qd_titleTextColor;
    titleLbel.font = [UIFont br_fontB:17];
    [top addSubview:titleLbel];
    [titleLbel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(backBtn);
    }];
  
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
